package mesweb.mesweb.controller.procedure;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farvision.common.api.CommonResult;
import com.farvision.common.exception.ApiException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import mesweb.mesweb.entity.Procedure.MesProduceProcedure;
import mesweb.mesweb.entity.produceLine.ModelProduceLine;
import mesweb.mesweb.service.procedure.IMesProduceProcedureService;
import mesweb.mesweb.service.procedure.IModelProduceLineBranchProcedureLineService;
import mesweb.mesweb.service.produceLine.IModelProduceLineBranchLineService;
import mesweb.mesweb.service.produceLine.IModelProduceLineService;
import mesweb.mesweb.vo.procecdure.MesProduceProcedureVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.List;

 /**
 * @Description: 生产工序
 * @Author: jeecg-boot
 * @Date:   2021-06-26
 * @Version: V1.0
 */

@Api(tags="生产工序")
@RestController
@RequestMapping("/mes/mesProduceProcedure")
public class MesProduceProcedureController {
	@Autowired
	private IMesProduceProcedureService mesProduceProcedureService;

	 @Autowired
	 private IModelProduceLineBranchProcedureLineService modelProduceLineBranchProcedureLineService;

	 @Autowired
	 private IModelProduceLineBranchLineService modelProduceLineBranchLineService;

	 @Autowired
	 private IModelProduceLineService modelProduceLineService;



	 @GetMapping("/GetAll")
    @ApiOperation("获取全部数据列表")
    public CommonResult<?> GetAll(@ApiParam("名称") @RequestParam( value = "name",required = false) String name) {
        List<MesProduceProcedureVo> data;
		QueryWrapper<MesProduceProcedureVo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isBlank(name) || name.equals("全部")) {
        }
		data = mesProduceProcedureService.getProduceProcedure(queryWrapper);
        return CommonResult.success(data);
    }
	/**
	 * 分页列表查询
	 *
	 * @param page
	 * @param size
	 * @param req
	 * @return
	 */
	@ApiOperation(value="生产工序-分页列表查询", notes="生产工序-分页列表查询")
	@GetMapping(value = "/list")
	public CommonResult<?> queryPageList(
			                       @RequestParam(name="no", required = false, defaultValue="") String produceProcedureNo,
								   @RequestParam(name="updateStartTime", required = false,defaultValue="") Timestamp updateStartTime,
								   @RequestParam(name="updateEndTime",required = false, defaultValue="") Timestamp updateEndTime,
								   @RequestParam(name="status",required = false,defaultValue= "-1") Integer status,
								   @RequestParam(name="page",required = false ,defaultValue="1") Integer page,
								   @RequestParam(name="size", required = false ,defaultValue="10") Integer size,
								   HttpServletRequest req) {
		QueryWrapper<MesProduceProcedureVo> queryWrapper = new QueryWrapper<>();
		if(produceProcedureNo != null && produceProcedureNo.length()>0)
		{
			queryWrapper.eq("a.Produce_Procedure_No",produceProcedureNo);
		}
		else {
			if (updateStartTime != null && updateEndTime != null) {
				queryWrapper.between("updateTime", updateStartTime, updateEndTime);
			}
			if (status != -1) {
				queryWrapper.eq("status", status);
			}
		}
		Page<MesProduceProcedureVo> pageMesProduceProcedureVo = new Page<MesProduceProcedureVo>(page, size);
		IPage<MesProduceProcedureVo> pageList = mesProduceProcedureService.getProduceProcedure(pageMesProduceProcedureVo, queryWrapper);
		return CommonResult.success(pageList);
	}
	/**
	 * 编辑
	 *
	 * @param mesProduceProcedure
	 * @return
	 */
	@ApiOperation(value="生产工序-编辑", notes="生产工序-编辑")
	@PostMapping(value = "/save")
	public CommonResult<?> edit(@RequestBody MesProduceProcedure mesProduceProcedure) {

		boolean result = false;
        if(mesProduceProcedure.getId() == 0L) {
			QueryWrapper<MesProduceProcedure> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("Produce_Procedure_No", mesProduceProcedure.getProduceProcedureNo());
			queryWrapper.or().eq("Produce_Procedure_Name", mesProduceProcedure.getProduceProcedureName());
			MesProduceProcedure mesTechnologyFlow1 = mesProduceProcedureService.getOne(queryWrapper);
			if (mesTechnologyFlow1 != null) {
				String msg = StrUtil.format("编号{}或名称{}已经存在！", mesTechnologyFlow1.getProduceProcedureNo(), mesTechnologyFlow1.getProduceProcedureName());
				throw new ApiException(msg);
			}
             result = mesProduceProcedureService.save(mesProduceProcedure);
        }
        else
        {
            result = mesProduceProcedureService.updateById(mesProduceProcedure);
        }
        return CommonResult.success(mesProduceProcedure);
	}

	 /**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="生产工序-通过id删除", notes="生产工序-通过id删除")
	@DeleteMapping(value = "/delete")
	public CommonResult<?> delete(@RequestParam(name="id",required=true) String id) {

		//有关联的ids
		HashSet<Long> hashSetIds = new HashSet<>();
		modelProduceLineBranchLineService.list().stream().filter(o-> { return id.equals(o.getSourceLineId()) && o.getSourceLineType() == 2;}).map(o-> { return hashSetIds.add(o.getProduceLineId());});

		if(hashSetIds.size()> 0)
		{
			ModelProduceLine modelProduceLine = modelProduceLineService.getById(hashSetIds.iterator().next());
			throw new ApiException(StrUtil.format("产线{}正在使用此生产工序线，请先删除产线！",modelProduceLine.getProduceLineName()));
		}

		mesProduceProcedureService.removeById(id);
		HashSet<Long> hashSet = new HashSet<>();
		modelProduceLineBranchProcedureLineService.list().stream().filter( o -> { return id.equals(o.getProcedureLineId());}).map( o -> {
			return  hashSet.add(o.getId());
		});
		if(hashSet.size()>0) {
			for (Long itm : hashSet
			) {
				modelProduceLineBranchProcedureLineService.removeById(itm);
			}
		}
		return CommonResult.success("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@ApiOperation(value="生产工序-批量删除", notes="生产工序-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	@Transactional(rollbackFor = Throwable.class)
	public CommonResult<?> deleteBatch(@ApiParam("MesProduceProcedureIDs") @RequestBody List<Long> ids) {
        //如果产线中存在未排产的产线和生产工序线有关联，则应该先删除产线才能删除生产工序线？
		//有关联的ids
		HashSet<Long> hashSetIds = new HashSet<>();
		modelProduceLineBranchLineService.list().stream().filter(o-> { return ids.contains(o.getSourceLineId()) && o.getSourceLineType() == 2;});

		if(hashSetIds.size()> 0)
		{
			ModelProduceLine modelProduceLine = modelProduceLineService.getById(hashSetIds.iterator().next());
			throw new ApiException(StrUtil.format("产线{}正在使用此生产工序线，请先删除产线！",modelProduceLine.getProduceLineName()));
		}

		//过滤掉有关联的ids,不给提示删除没关联的？
		ids.removeIf(o-> {
			return hashSetIds.contains(o);
		});

		this.mesProduceProcedureService.removeByIds(ids);
		HashSet<Long> hashSet = new HashSet<>();
		modelProduceLineBranchProcedureLineService.list().stream().filter( o -> { return ids.contains(o.getProcedureLineId());}).map( o -> {
			return  hashSet.add(o.getId());
		});
		if(hashSet.size()>0) {
			for (Long itm : hashSet
			) {
				modelProduceLineBranchProcedureLineService.removeById(itm);
			}
		}
		return CommonResult.success("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="生产工序-通过id查询", notes="生产工序-通过id查询")
	@GetMapping(value = "/queryById")
	public CommonResult<?> queryById(@RequestParam(name="id",required=true) String id) {
		MesProduceProcedure mesProduceProcedure = mesProduceProcedureService.getById(id);
		return CommonResult.success(mesProduceProcedure);
	}
}
